package com.algrithom.array;

/**
 * 1005. K 次取反后最大化的数组和
 */
public class Solution11 {
    public static void main(String[] args) {
        int[] nums = new int[]{4,2,3};
        Solution11 solution11 = new Solution11();
        System.out.println(solution11.largestSumAfterKNegations(nums,2));
    }

    public int largestSumAfterKNegations(int[] A, int K){
        int[] nums = new int[201];
        for (int ar : A) {
            nums[100 + ar]++;
        }
        int count = K;
        int i=0;
        while (count > 0) {
            while (nums[i] == 0) {
                i++;
            }
            nums[i]--;
            nums[200 -i]++;
            if (i > 100) {
                i = 200 - i;
            }
            count--;
        }
        int sum = 0;
        for (int j=i;j<nums.length;j++) {
            sum += (j - 100) * nums[j];
        }
        return sum;
    }
}
